package com.shadow.bus.main.search_code;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.SearchPersonCodeBean;
import com.shadow.bus.event.SearchPersonEvent;
import com.shadow.bus.tools.SPUtils;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.tepth.shadow.ui.recycler.BaseDecoration;
import com.tepth.shadow.ui.search.SearchClearEditText;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.screen.DimensionConvert;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;

import org.greenrobot.eventbus.EventBus;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import busfix.tepth.com.shadow_bus.R;
import io.reactivex.disposables.Disposable;

/**
 * @author zhangyu
 * @date 2018/10/12
 */

public class NameFragment extends DialogFragment {
    public static NameFragment newInstance() {
        return new NameFragment();
    }

    private RecyclerView mRecyclerViewSearch;
    private SearchClearEditText mEditText;
    private Disposable mDisposable;
    private SearchPersonAdapter mSearchPersonAdapter;
    private DialogDelegate mDialogDelegate;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.fragment_input_name);
        dialog.setCanceledOnTouchOutside(true);

        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.CENTER;
            lp.height = DimensionConvert.getHeight2(getContext());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(lp);
        }
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
        mRecyclerViewSearch = dialog.findViewById(R.id.recycler_view_search);
        mRecyclerViewSearch.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerViewSearch.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchPersonCodeBean bean = (SearchPersonCodeBean) adapter.getItem(position);
                if (bean != null) {
                    HashMap<String, String> hashMap = (HashMap<String, String>) SPUtils.getObject(getContext(), SpKey.KEY_HISTORY_USER);
                    if (hashMap == null) {
                        hashMap = new HashMap<>();
                    }
                    hashMap.put(bean.getCode(), bean.getName());
                    SPUtils.putObject(getContext(), SpKey.KEY_HISTORY_USER, hashMap);
                    EventBus.getDefault().post(new SearchPersonEvent(bean.getName(), bean.getCode()));
                }
                dismiss();
            }
        });
        final HashMap<String, String> hashMap = (HashMap<String, String>) SPUtils.getObject(getContext(), SpKey.KEY_HISTORY_USER);
        RecyclerView recyclerViewHistory = dialog.findViewById(R.id.recycler_view_history);
        recyclerViewHistory.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewHistory.addItemDecoration(BaseDecoration.create(ContextCompat.getColor(getContext(),
                R.color.app_background), 1));
        recyclerViewHistory.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                final SearchPersonCodeBean bean = (SearchPersonCodeBean) adapter.getItem(position);
                if (bean != null) {
                    mDialogDelegate.showWarningDialog(bean.getName(), "请确认选择",
                            new DialogDelegate.OnDialogListener() {
                                @Override
                                public void onClick() {
                                    EventBus.getDefault().post(new SearchPersonEvent(bean.getName(), bean.getCode()));
                                    dismiss();
                                }
                            }, true);
                }
            }

            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                final SearchPersonCodeBean bean = (SearchPersonCodeBean) adapter.getItem(position);
                if (bean != null) {
                    if (view.getId() == R.id.layout_iv) {
                        mDialogDelegate.showWarningDialog("请确定", "确定要删除" + bean.getName() + "么?"
                                , new DialogDelegate.OnDialogListener() {
                                    @Override
                                    public void onClick() {
                                        adapter.remove(position);
                                        if (hashMap != null) {
                                            hashMap.remove(bean.getCode());
                                            SPUtils.putObject(getContext(), SpKey.KEY_HISTORY_USER, hashMap);
                                        }
                                    }
                                }, true);
                    }
                }
            }
        });
        mSearchPersonAdapter = new SearchPersonAdapter(R.layout.item_person_name, null);
        mRecyclerViewSearch.setAdapter(mSearchPersonAdapter);
        //历史
        final HistoryPersonAdapter historyPersonAdapter = new HistoryPersonAdapter(R.layout.item_person_history_name, null);
        if (hashMap != null) {
            List<Map.Entry<String, String>> list = new ArrayList<>(hashMap.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
                //升序排序
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return Collator.getInstance(Locale.CHINESE).compare(o1.getValue(), o2.getValue());
                }
            });
            List<SearchPersonCodeBean> beans = new ArrayList<>();
            for (Map.Entry<String, String> e : list) {
                SearchPersonCodeBean bean = new SearchPersonCodeBean();
                bean.setCode(e.getKey());
                bean.setName(e.getValue());
                beans.add(bean);
            }

            recyclerViewHistory.setAdapter(historyPersonAdapter);
            historyPersonAdapter.setNewData(beans);
            historyPersonAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) recyclerViewHistory.getParent());
        }

        mEditText = dialog.findViewById(R.id.et_search);
        mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearch(mEditText.getText().toString().trim());
                    return true;
                }
                return false;
            }
        });
        dialog.findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogDelegate.showWarningDialog("清空历史记录", "请确定是否需要清空历史记录!"
                        , new DialogDelegate.OnDialogListener() {
                            @Override
                            public void onClick() {
                                historyPersonAdapter.setNewData(null);
                                SPUtils.remove(getContext(), SpKey.KEY_HISTORY_USER);
                            }
                        }, true);
            }
        });
        return dialog;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    private void onSearch(String trim) {
        if (trim.isEmpty()) {
            return;
        }
        mSearchPersonAdapter.setEmptyView(R.layout.view_loading, (ViewGroup) mRecyclerViewSearch.getParent());
        mDisposable = RxRestClient.builder()
                .url(ServiceUrl.SEARCH_PERSON_CODE)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("code", trim)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mSearchPersonAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerViewSearch.getParent());
                        SearchPersonCodeBean bean = new SearchNameDataConverter().convert(response);
                        if (bean != null) {
                            List<SearchPersonCodeBean> list = new ArrayList<>();
                            list.add(bean);
                            mSearchPersonAdapter.setNewData(list);
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mSearchPersonAdapter.setEmptyView(R.layout.view_empty, (ViewGroup) mRecyclerViewSearch.getParent());
                    }
                })
                .build()
                .post();
    }
}
